package com.cdu.guoxinan.www.smartcom.service.impl;

import com.cdu.guoxinan.www.smartcom.domian.dto.ParkingSpotQueryDTO;
import com.cdu.guoxinan.www.smartcom.domian.pojo.ParkingSpot;
import com.cdu.guoxinan.www.smartcom.domian.pojo.Vehicle;
import com.cdu.guoxinan.www.smartcom.domian.vo.ParkingSpotVO;
import com.cdu.guoxinan.www.smartcom.mapper.ParkingSpotMapper;
import com.cdu.guoxinan.www.smartcom.mapper.VehicleMapper;
import com.cdu.guoxinan.www.smartcom.service.ParkingSpotService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ParkingSpotServiceImpl implements ParkingSpotService {

    @Resource
    private ParkingSpotMapper parkingSpotMapper;

    @Resource
    private VehicleMapper vehicleMapper;

    @Override
    public PageInfo<ParkingSpotVO> queryPage(ParkingSpotQueryDTO parkingSpotQueryDTO) {
        PageHelper.startPage(parkingSpotQueryDTO.getPage(), parkingSpotQueryDTO.getLimit());
        List<ParkingSpotVO> list = parkingSpotMapper.queryPage(parkingSpotQueryDTO);
        return new PageInfo<>(list);
    }

    @Override
    public boolean add(ParkingSpot parkingSpot) {
        return parkingSpotMapper.add(parkingSpot) > 0;
    }

    @Override
    public boolean update(ParkingSpot parkingSpot) {
        return parkingSpotMapper.update(parkingSpot) > 0;
    }

    @Override
    public boolean delete(Long id) {
        return parkingSpotMapper.delete(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean release(ParkingSpot parkingSpot) {
        // 1. 将停车位状态从 2 改为 1
        parkingSpot.setParkingSpotStatus(1);
        int result1 = parkingSpotMapper.update(parkingSpot);

        // 2. 删除车辆表中 parkingSpotId 的引用
        int result2 = parkingSpotMapper.releaseParkingSpotById(parkingSpot.getParkingSpotId());

        return result1 > 0 && result2 >= 0; // 允许没有车辆关联
    }
}
